package com.itheima.controller;


import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: 周训发
 * @CreateTime: 2025-10-21
 * @Description: 接收前端上传的文件
 * @Version: 1.0
 */

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/upload")
//    public Result upload(String username, Integer age, MultipartFile image) throws Exception {
    public Result upload(MultipartFile image) throws Exception {


//        //获取原始文件名
//        String originalFilename = image.getOriginalFilename();
//        //获取文件后缀名
//        //1. 获取最后一个点的位置
//        int index = originalFilename.lastIndexOf(".");
//        //2. 截取字符串subString()
//        String extname = originalFilename.substring(index);
//        //进行拼接组成新的文件名
//        String newFileName = UUID.randomUUID() + extname;
//        log.info("获取到的新文件名：{}",newFileName);
//        //放在指定文件夹中进行存储
//        File file = new File("F:\\TEST\\junk\\image\\" + newFileName);
//        image.transferTo(file);
        try {
            //原始文件名
            String originalFilename = image.getOriginalFilename();
            //截取原始文件名的后缀.jpg等,获得扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String fillPath = aliOSSUtils.upload(image.getBytes(), objectName);
            return Result.success(fillPath);
        } catch (IOException e) {
            log.info("文件上传失败：{}",e);
        }

        return null;
    }
}
